package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.data.attribute.Name;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.Output;
import org.akomantoso.core.io.OutputUtil;
import org.akomantoso.core.io.util.ContainerElementUtil;
import org.akomantoso.core.visitor.AKVisitor;

/**
 * the complex type containerType is the content model for the generic element for a container. It can be placed in a
 * container instead of any of the other containers. The attribute name is required and gives a name to the element.
 * 
 * <pre>
 *  <xsd:complexType name="containerType">
 * 		<xsd:choice minOccurs="1" maxOccurs="unbounded">
 * 			<xsd:group ref="blockElements"/>
 * 			<xsd:element ref="container"/>
 * 		</xsd:choice>
 * 		<xsd:attributeGroup ref="corereq"/>
 * 		<xsd:attributeGroup ref="name"/>
 * 	</xsd:complexType>
 * </pre>
 * 
 */
public abstract class ContainerType extends CoreReqImpl implements Name {

	private String _name;
	
	private final List<ContainerElement> _elements = new ArrayList<ContainerElement>(8);
	
	/**
	 * @see org.akomantoso.core.data.attribute.Name#getName()
	 */
	@Override
	public String getName() {
		return _name;
	}
	
	/**
	 * @see org.akomantoso.core.data.attribute.Name#setName(java.lang.String)
	 */
	@Override
	public void setName(String name) {
		_name = name;
	}
	
	public List<ContainerElement> getElements() {
		return _elements;
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	@Override
	public <T extends Output> void writeExternal(T out) throws IOException {
		super.writeExternal(out);
		OutputUtil.writeName(out, this);
		for (int i = 0 , n = _elements .size() ; i < n ; i++) {
			_elements.get(i).writeExternal(out);
		}
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	@Override
	public <T extends Input> void readExternal(T in) throws IOException {
		super.readExternal(in);
		_name = in.readAttribute(Name.ATTRIBUTE);
		final String localName = in.getLocalName();
		in.readNextStartElement();
		ContainerElementUtil.read(in, _elements, localName);
	}

	protected final void internalAccept(AKVisitor visitor) {
		for (int i = 0 , n = _elements .size() ; i < n ; i++) {
			_elements.get(i).accept(visitor);
		}
	}
	
}
